package com.example.send.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ImageUtil {

//    private static final String POST_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + AuthService.getAuth();
    private static final String POST_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + AuthService.getAuth();

    /**
     * 识别本地图片的文字
     */
    public static String checkFile(String path) throws URISyntaxException, IOException {
        File file = new File(path);
        if (!file.exists()) {
            throw new NullPointerException("图片不存在");
        }
        String image = BaseImg64.getImageStrFromPath(path);
        String param = "image=" + image;
        return post(param);
    }

    /**
     * 图片url
     * 识别结果，为json格式
     */
    public static String checkUrl(String url) throws IOException, URISyntaxException {
        String param = "url=" + url;
        return post(param);
    }

    /**
     * 通过传递参数：url和image进行文字识别
     */
    private static String post(String param) throws URISyntaxException, IOException {
        //开始搭建post请求
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost();
        URI url = new URI(POST_URL);
        post.setURI(url);
        //设置请求头，请求头必须为application/x-www-form-urlencoded，因为是传递一个很长的字符串，不能分段发送
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");
        StringEntity entity = new StringEntity(param);
        post.setEntity(entity);
        HttpResponse response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
            String str;
            try {
                //读取服务器返回过来的json字符串数据
                str = EntityUtils.toString(response.getEntity());
                return str;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    public static void main(String[] args) throws InterruptedException {
        String regex = "[\\u4e00-\\u9fa5]+";
        String path = "E:\\back_project\\python\\hanzi\\1\\";
        File ffile = new File(path);
        File[] fs = ffile.listFiles();
        Set<String> set = new HashSet<>();
        for (File f : fs) {
//        File f = new File("E:\\back_project\\python\\hanzi\\49\\44.jpg");
            if (!f.isDirectory()) {
                System.out.println(f.getAbsolutePath());
                try {
                    String str = checkFile(f.getAbsolutePath());
                    System.out.println(str);
                    JSONObject object = JSONObject.parseObject(str);
                    JSONArray array = object.getJSONArray("words_result");
                    String word = "";
                    if (array != null && array.size() > 0) {
                        for (int i = 0; i < array.size(); i++) {
                            JSONObject in = array.getJSONObject(i);
                            String temp = in.getString("words");
                            Matcher m = Pattern.compile(regex).matcher(temp);
                            if (m.find()) {
                                word = temp;
                                break;
                            }
                        }

                    }
                    if (word != null && word.length() > 0) {
                        if (set.contains(word)) {
                            System.out.println("出现重复：" + f.getAbsolutePath() + "-----" + word);
                            continue;
                        } else {
                            set.add(word);
                        }
                        f.renameTo(new File(path + word + ".jpg"));
                    }
                } catch (URISyntaxException | IOException e) {
                    e.printStackTrace();
                }
            }
            Thread.sleep(1000);
        }
    }
}
